package com.foodcommunity.service.impl;

import com.foodcommunity.common.Result;
import com.foodcommunity.dto.CommentDTO;
import com.foodcommunity.entity.Comment;
import com.foodcommunity.entity.FoodPost;
import com.foodcommunity.mapper.CommentMapper;
import com.foodcommunity.mapper.FoodPostMapper;
import com.foodcommunity.service.CommentService;
import com.foodcommunity.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;
    
    @Autowired
    private FoodPostMapper foodPostMapper;

    @Override
    @Transactional
    public Result<Comment> addComment(CommentDTO commentDTO, Long userId) {
        // 验证帖子是否存在
        FoodPost post = foodPostMapper.selectById(commentDTO.getPostId());
        if (post == null) {
            return Result.error("帖子不存在");
        }
        
        // 如果有父评论，验证父评论是否存在
        if (commentDTO.getParentId() != null) {
            Comment parentComment = commentMapper.selectById(commentDTO.getParentId());
            if (parentComment == null) {
                return Result.error("父评论不存在");
            }
        }
        
        // 处理图片上传
        String images = null;
        if (commentDTO.getImageFiles() != null && commentDTO.getImageFiles().length > 0) {
            List<String> imageUrls = new ArrayList<>();
            for (MultipartFile file : commentDTO.getImageFiles()) {
                if (!file.isEmpty()) {
                    try {
                        String imageUrl = FileUploadUtil.saveFile(file);
                        imageUrls.add(imageUrl);
                    } catch (Exception e) {
                        return Result.error("图片上传失败: " + e.getMessage());
                    }
                }
            }
            if (!imageUrls.isEmpty()) {
                images = String.join(",", imageUrls);
            }
        }
        
        // 创建评论
        Comment comment = new Comment();
        comment.setPostId(commentDTO.getPostId());
        comment.setUserId(userId);
        comment.setContent(commentDTO.getContent());
        comment.setParentId(commentDTO.getParentId());
        comment.setCreateTime(LocalDateTime.now());
        comment.setImages(images);
        
        int rows = commentMapper.insert(comment);
        if (rows > 0) {
            return Result.success(comment);
        }
        return Result.error("评论失败");
    }

    @Override
    @Transactional
    public Result<Void> deleteComment(Long id, Long userId) {
        Comment comment = commentMapper.selectById(id);
        if (comment == null) {
            return Result.error("评论不存在");
        }
        
        // 验证是否是评论作者
        if (!comment.getUserId().equals(userId)) {
            return Result.error("无权删除此评论");
        }
        
        // 检查是否有子评论
        List<Comment> childComments = commentMapper.selectByParentId(id);
        if (childComments != null && !childComments.isEmpty()) {
            return Result.error("该评论有回复，无法删除");
        }
        
        int rows = commentMapper.delete(id);
        if (rows > 0) {
            return Result.success(null);
        }
        return Result.error("删除失败");
    }

    @Override
    public List<Comment> getPostComments(Long postId) {
        return commentMapper.selectByPostId(postId);
    }

    @Override
    public Result<Comment> getCommentDetail(Long id) {
        Comment comment = commentMapper.selectById(id);
        if (comment == null) {
            return Result.error("评论不存在");
        }
        return Result.success(comment);
    }

    @Override
    public List<Comment> getChildComments(Long parentId) {
        return commentMapper.selectByParentId(parentId);
    }

    @Override
    public List<Comment> getPostCommentsWithPage(Long postId, int page, int size) {
        int offset = (page - 1) * size;
        return commentMapper.selectByPostIdWithPage(postId, offset, size);
    }

    @Override
    public int getPostCommentCount(Long postId) {
        return commentMapper.countByPostId(postId);
    }

    @Override
    public List<Comment> getUserComments(Long userId) {
        return commentMapper.selectByUserId(userId);
    }
} 